use serde::{Deserialize, Serialize};
use crate::media::volume::{get_volume, set_volume};
use crate::web_rtc::code_rate::{get_audio_code_rate, get_video_code_rate, set_audio_code_rate, set_video_code_rate};
use crate::media::media_ctrl::{get_audio_available, get_video_available, set_audio_available, set_video_available};
use crate::web_rtc::turn::TurnServerConfig;
use axum::Json;
use crate::controller::reverse::{get_x_reverse, get_y_reverse, set_x_reverse, set_y_reverse};
use crate::web_rtc::off_line_time::{get_off_line_time, set_off_line_time};
use crate::db::db_delete::db_delete_all;

#[derive(Serialize, Deserialize, Debug)]
pub struct Setting {
    Volume: u8, // 0-100
    // 单位kbps
    VideoCodeRate: u32,
    AudioCodeRate: u32,
    VideoAvailable: bool,
    AudioAvailable: bool,
    TurnServer: Option<TurnServer>,
    X_Axis_Reverse: bool,
    Y_Axis_Reverse: bool,
    // 单位分钟
    AutomaticOfflineTime: u64,
}


#[derive(Serialize, Deserialize, Debug, Default)]
struct TurnServer {
    Server: String,
    Username: String,
    Password: String,
}

pub async fn get_setting() -> Json<Setting> { 
    let mut turn_server = TurnServer::default();
    if let Some(TurnServer) = TurnServerConfig::get().await {
        turn_server = TurnServer {
            Server: TurnServer.server,
            Username: TurnServer.username,
            Password: TurnServer.password,
        };
    }
    let setting = Setting {
        Volume: get_volume().await,
        VideoCodeRate: get_video_code_rate().await,
        AudioCodeRate: get_audio_code_rate().await,
        VideoAvailable: get_video_available().await,
        AudioAvailable: get_audio_available().await,
        TurnServer: Some(turn_server),
        X_Axis_Reverse: get_x_reverse().await,
        Y_Axis_Reverse: get_y_reverse().await,
        AutomaticOfflineTime: get_off_line_time().await,
    };
    return Json(setting);
}

pub async fn set_setting(Json(payload): Json<Setting>) {
    set_volume(payload.Volume).await;
    set_video_code_rate(payload.VideoCodeRate).await;
    set_audio_code_rate(payload.AudioCodeRate).await;
    set_video_available(payload.VideoAvailable).await;
    set_audio_available(payload.AudioAvailable).await;
    if let Some(turn) = payload.TurnServer{
        TurnServerConfig::set(&turn.Server, &turn.Username, &turn.Password).await;
    }
    set_x_reverse(payload.X_Axis_Reverse).await;
    set_y_reverse(payload.Y_Axis_Reverse).await;
    set_off_line_time(payload.AutomaticOfflineTime).await;
}

pub async fn logout() {
    db_delete_all().await.unwrap();
}